/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-12 18:58:05
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-21 10:58:11
 */
// components/scrollWrap/index.js
Component({

  externalClasses: ['custom-class'],
  /**
   * 组件的属性列表
   */
  properties: {
    requestObject: Object,
    isRefresh:{
      type:Boolean,
      default:true
    },
    customStyle:String
  },

  /**
   * 组件的初始数据
   */
  data: {
    canRefresh: false,
    loadMore: false,
    noMore: false,
    triggered: false,
    isRefreshing: false,
    pageNum: 1
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getData(refresh) {
      // console.log(this.data.requestObject)
      return new Promise(async (resolve, reject) => {
        try {
          this.pages = await this.data.requestObject.fetchData(refresh)
          resolve(this.pages)
        } catch (error) {
           reject(false)
        }
      })
    },
    beforeRefresh(e) {
      if(this.data.isRefresh) return false
      const {
        dy
      } = e.detail
      this.setData({
        canRefresh: dy >= 45
      })
    },
    resetRefresh() {
      if(this.data.isRefresh) return false
      this.setData({
        canRefresh: false,
        isRefreshing: false,
        noMore: false,
        loadMore: this.page<9
      })
    },
    onRefresh() {
      if(this.data.isRefresh) return false
      if (this._freshing) return
      this._freshing = true
      this.setData({
        pageNum: 1,
        noMore: false,
        loadMore: true,
        triggered: true,
        isRefreshing: true
      })
      setTimeout(() => {
        this.getData(true).then(res => {
          if (res!=null) {
            this.setData({
              triggered: false,
            })
          }
        })
        this._freshing = false
        this._loadMore = false
      }, 300)
    },
    // 上拉加载更多
    loadMore: function () {
      if (this._loadMore) return
      this._loadMore = true
      var self = this;
      // 当前页是最后一页
      if (self.pages < 10) {
        self.setData({
          noMore: true,
          loadMore: false
        })
        return;
      }
      this.setData({
        loadMore: true,
        isRefreshing: false
      })
      setTimeout(function () {
        self.getData().then(pages => {
          if (pages < 10) {
            self.setData({
              noMore: true,
              loadMore: false
            })
            return
          }
          // 判断是否到底部
          self._loadMore = false
          self.setData({
            noMore: false,
            loadMore: true
          })
        })
      }, 300);
    },
  }
})